package com.muqi.app.pj.shops;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.pj.shops.MineOrderAdapter.onPayDeleteListener;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.qlearn.student.BaseFragment;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class GoodFragment extends BaseFragment implements OnClickListener,
		XListView.IXListViewListener, OnItemClickListener, onPayDeleteListener {
	protected int uiType = 0; /* 0 实物订单列表 1 虚拟订单列表 */
	private XListView mListview;
	private int page = 1;
	private List<OrderBean> dataList;
	private MineOrderAdapter mAdapter;
	private RefreshReceiver receiver;

	public GoodFragment(int uiType) {
		super();
		this.uiType = uiType;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IntentFilter intentFilter = new IntentFilter();
		receiver = new RefreshReceiver();
		intentFilter.addAction("Back_Goods");
		mActivity.registerReceiver(receiver, intentFilter); // 注册监听
	}

	@SuppressLint("InflateParams")
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

		return LayoutInflater.from(mActivity).inflate(
				R.layout.fragment_good_order, null);

	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (uiType == 0) {

		} else if (uiType == 1) {

		}
		mListview = (XListView) view.findViewById(R.id.listview);
		mListview.setXListViewListener(this);
		mListview.setPullRefreshEnable(true);
		loadData();

	}

	/**
	 * 加载数据
	 */
	private void loadData() {
		loadingData();
	}

	private void loadingData() {
		HashMap<String, Object> getMap = new HashMap<String, Object>();
		getMap.put("token", mSpUtil.getToken());
		getMap.put("page", page);
		if (uiType == 0) {
			getMap.put("type", 0);
		} else {
			getMap.put("type", 1);
			getMap.put("student_id", mSpUtil.getCurrentChildId());
		}
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.Mine_Order_List_Api, getMap);
		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				mListview.stopRefresh();
				mListview.stopLoadMore();
				mListview.setRefreshTime("刚刚");
				if (resuleCode == RESULTCODE.SUCCESS) {
					ArrayList<OrderBean> temp = null;
					if (uiType == 0) {
						temp = ResponseUtils.getOrderList(mActivity, result);
					} else {
						temp = ResponseUtils
								.getXuniOrderList(mActivity, result);

					}
					Log.e("===", temp.size() + "temp");
					if (temp != null) {
						showList(temp);
					}

				}

			}
		});

	}

	private void showList(List<OrderBean> getList) {
		if (getList.size() < 10) {
			mListview.setPullLoadEnable(false);
		} else {
			mListview.setPullLoadEnable(true);
		}
		if (page == 1) {

			dataList = getList;
			if (mAdapter != null) {
				mAdapter = null;
			}
			mAdapter = new MineOrderAdapter(mActivity, dataList);
			mAdapter.setCheckListener(this);
			mListview.setAdapter(mAdapter);
		} else {

			for (OrderBean item : getList) {
				dataList.add(item);
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public void onRefresh() {
		page = 1;
		loadingData();
	}

	@Override
	public void onLoadMore() {
		page++;
		loadingData();
	}

	//
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	@Override
	public void onDestroy() {
		mActivity.unregisterReceiver(receiver);
		super.onDestroy();
	}

	private class RefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action != null && action.equals("Back_Goods")) {
				int position = intent.getIntExtra("position", -1);
				int parrentPos = intent.getIntExtra("parrentPos", -1);
				if (position != -1 && parrentPos != -1) {
					dataList.get(parrentPos).getDingdan_mx().get(position)
							.setTuihuo_zhuangtai("1");
					mAdapter.notifyDataSetChanged();
				}
			}
		}
	}

	@Override
	public void onPay(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDuiHuan(int position) {
		Intent intent = new Intent(mActivity, OrderIdActivity.class);
		intent.putExtra("orderId", dataList.get(position).getDingdanhao());
		intent.putExtra("payMoney", dataList.get(position).getZongji() + "");
		if (uiType == 0) {
			intent.putExtra("type", 0);
		} else {
			intent.putExtra("type", 1);
			
		}
		startActivity(intent);

	}

	@Override
	public void onDelete(final int position) {
		new SweetAlertDialog(mActivity, SweetAlertDialog.WARNING_TYPE)
				.setTitleText("确定要删除该条订单吗").setCancelText("取消")
				.setConfirmText("确定").showCancelButton(true)
				.setCancelClickListener(new OnSweetClickListener() {
					@Override
					public void onClick(SweetAlertDialog mDialog) {
						mDialog.dismissWithAnimation();
					}
				}).setConfirmClickListener(new OnSweetClickListener() {
					@Override
					public void onClick(SweetAlertDialog mDialog) {
						mDialog.getProgressHelper().setBarColor(
								Color.parseColor("#A5DC86"));
						mDialog.setTitleText("正在删除").showCancelButton(false)
								.setCancelable(false);
						mDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);

						loadingDelete(position, mDialog);
					}
				}).show();

	}

	protected void loadingDelete(final int position,
			final SweetAlertDialog mDialog) {
		if (NetWorkUtils.isNetworkAvailable(mActivity)) {
			HashMap<String, Object> voteMap = new HashMap<String, Object>();
			voteMap.put("token", mSpUtil.getToken());
			voteMap.put("dingdan_id", dataList.get(position).getDingdan_id());
			String requestApi = ParamsUtils.buildParams(
					NetWorkApi.Mine_Order_Delete_Api, voteMap);
			MyAsyncHttp.get(mActivity, requestApi, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					mDialog.dismissWithAnimation();
					dataList.remove(position);
					if (mAdapter != null)
						mAdapter.notifyDataSetChanged();

				}
			});

		}
	}

}